


#include "phDriver.h"
#include <DAL/cfg/BoardSelection.h>
#include <BSP.h>

#define PHBAL_REG_GD32_SPI_ID               0x0EU       /**< ID for LPC Open SPI BAL component */

phStatus_t phbalReg_Init(void * pDataParams,
                             uint16_t wSizeOfDataParams
                             )
{
    if((pDataParams == NULL) || (sizeof(phbalReg_Type_t) != wSizeOfDataParams))
    {
        return (PH_DRIVER_ERROR | PH_COMP_DRIVER);
    }
	RFIO_Init();
    ((phbalReg_Type_t *)pDataParams)->wId      = PH_COMP_DRIVER | PHBAL_REG_GD32_SPI_ID;
    ((phbalReg_Type_t *)pDataParams)->bBalType = PHBAL_REG_TYPE_SPI;
    return PH_DRIVER_SUCCESS;
}

#if 0
static void SPI_WriteBlock(const uint8_t* TxBuf, uint32_t TxLen){
	for(uint32_t i = 0; i < TxLen; i++){
		RFIO_SPI_Exchange(TxBuf[i]);
	}
}

static void SPI_ReadBlock(uint8_t* RxBuf, uint32_t RxLen){
	for(uint32_t i = 0; i < RxLen; i++){
		RxBuf[i] = RFIO_SPI_Exchange(0xFF);
	}
}
#endif 

static void SPI_ExchangeBlock(const uint8_t* TxBuf, uint32_t TxLen, uint8_t* RxBuf, uint32_t RxLen){
	uint32_t ti = 0;
	uint32_t ri = 0;
	uint8_t td;
	uint8_t rd;
	
	while(ti < TxLen || ri < RxLen){
		if(ti < TxLen){
			td = TxBuf[ti];
			ti++;
		}
		else{
			td = 0xFF;
		}
		
		rd = RFIO_SPI_Exchange(td);
		
		if(ri < RxLen){
			RxBuf[ri] = rd;
			ri++;
		}
	}
}

phStatus_t phbalReg_Exchange(
                                        void * pDataParams,
                                        uint16_t wOption,
                                        uint8_t * pTxBuffer,
                                        uint16_t wTxLength,
                                        uint16_t wRxBufSize,
                                        uint8_t * pRxBuffer,
                                        uint16_t * pRxLength
                                        )
{
	SPI_ExchangeBlock(pTxBuffer, wTxLength, pRxBuffer, wRxBufSize);
	
    if ( pRxLength != NULL){
		if(wTxLength == 0){
			*pRxLength = wRxBufSize;
		}
		else{
			*pRxLength = wTxLength;
		}
	}
	
    return PH_DRIVER_SUCCESS;
}

phStatus_t phbalReg_SetConfig(
                                         void * pDataParams,
                                         uint16_t wConfig,
                                         uint16_t wValue
                                         )
{
    return PH_DRIVER_SUCCESS;
}

phStatus_t phbalReg_GetConfig(
                                         void * pDataParams,
                                         uint16_t wConfig,
                                         uint16_t * pValue
                                         )
{
    return PH_DRIVER_SUCCESS;
}

